<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-30 11:43:25
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2023-10-24 09:54:22
-->
<template>
	<div>
    <div class="flex">
		<el-button type="danger" @click="handleRefresh" style="margin-right: 15px;">列表刷新</el-button>
		<el-input v-model="query" placeholder="请输入行政区划名称" @input="onQueryChanged" class="mr8"/>
    </div>
		<el-tree
			ref="treeRef"
			class="mt10" v-if="!loading"
			:data="treeData"
			node-key="administrationId"
			draggable
			:filter-node-method="filterMethod"
			:props="defaultProps"
			:default-expanded-keys="defaultCheckedKeys"
			highlight-current
			:expand-on-click-node="false"
			@node-click="(e) => handleOperate('detail', e, '详情')"
			@node-drag-start="dragStart"
			@node-drop="handleDrop"
		>
			<template #default="{ node, data }">
				<span class="f-between w-100" @mouseenter="onMouseenter(node, data)" @mouseleave="onMouseleave(node, data)">
					<span
						:style="{
							color: node.data.administrationId === currentId ? '#1f5aff' : '',
							'margin-right': '2rem',
						}"
					>
						{{ node.label }}
					</span>
					<span v-show="data.show">
						<template v-if="data.administrationId !== -1">
							<el-button type="primary" text @click.stop="handleOperate('edit', data, node)">
								<icon-file-editing-one theme="outline" fill="#333" />
								编辑
							</el-button>
							<el-button type="primary" text @click.stop="handleOperate('add', data, node)">
								<icon-add-subset theme="outline" fill="#333" />
								添加下级
							</el-button>
							<el-button type="danger" text @click="handleDelete(node, data)">
								<icon-delete theme="outline" />
								删除
							</el-button>
							<el-button type="primary" text>
								<icon-drag theme="outline" fill="#333" />
								移动位置
							</el-button>
						</template>
						<template v-else>
							<el-button type="primary" text @click.stop="handleOperate('add', data, '添加下级')">
								<icon-add-subset theme="outline" fill="#333" />
								添加下级
							</el-button>
						</template>
					</span>
				</span>
			</template>
		</el-tree>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { ElMessageBox,ElMessage } from 'element-plus'
import { useCrudStore } from '@/stores/crud'
import { ElLoading } from 'element-plus'
import { useCommonStore } from '@/stores/common'

const { setAreaTreeData } = useCrudStore()
const emit = defineEmits(['tree-load', 'change'])
const query = ref('')
const treeData = ref([])
const treeRef = ref()
const currentId = ref()
const loading = ref(false)
const defaultCheckedKeys = ref([])
const props = defineProps({
	api: [String, Number],
})
const defaultProps = {
	value: 'administrationId',
	label: 'administrationName',
	children: 'children',
}

const { setTreeRefreshData } = useCommonStore()
const { treeRefreshData } = storeToRefs(useCommonStore())

const onQueryChanged = (query: string) => {
	treeRef.value!.filter(query)
}
const filterMethod = (value: string, data: any) => {
	if (!value) return true
	return data.administrationName.includes(value)
}

const dragStart = (node) => {
	currentId.value = node.data.id
}
// const allowDrop = (dragNode, dropNode, type) => {
//   const dgData = dragNode.data,
//     dpData = dropNode.data
//   return dgData.level === dpData.level && dpData.administrationId !== -1
// }

const onMouseenter = (node, data) => {
	data.show = true
}
const onMouseleave = (node, data) => {
	data.show = false
}
const handleOperate = (type, data, title) => {
	const row = JSON.parse(JSON.stringify(data))
	emit('change', type, row, title)
}
const getInitData = () => {
  loading.value = true 
	apiMod[props.api]({type:1}).then((res) => {
    loading.value = false
    if( Array.isArray(res.data)) {
      treeData.value = res.data
    }else {
      treeData.value = JSON.parse(res.data)
    }
    const checkedKeys = treeData.value.map(item=> {
      const ids = item.children.map(v=>v.id)
      return [...ids,item.id]
    })
    defaultCheckedKeys.value = checkedKeys.flat()
		setAreaTreeData(treeData.value)
		emit('tree-load', treeData.value)
	})
}

const pageReload: any = inject('reload')
const handleRefresh = ()=> {
  const loading = ElLoading.service({
    lock: true,
    text: '处理中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  apiMod[props.api]({type:0}).then((res) => {
    if( Array.isArray(res.data)) {
      treeData.value = res.data
    }else {
      treeData.value = JSON.parse(res.data)
    }
    const checkedKeys = treeData.value.map(item=> {
      const ids = item.children.map(v=>v.id)
      return [...ids,item.id]
    })
    defaultCheckedKeys.value = checkedKeys.flat()
    loading.close()
		setAreaTreeData(treeData.value)
		emit('tree-load', treeData.value)
		pageReload()
		setTreeRefreshData(2)
	}).catch(()=> {
     loading.close()
	 pageReload()
  })

}

const updateDrag = (data) => {
	// 更新数据
	apiMod
		.admin_sysadministration_edit({
			...data,
		})
		.then((res) => {
			ElMessage.success('调整成功')
			getInitData()
		})
		.catch(() => {
			getInitData()
		})
}

const handleDrop = (draggingNode, dropNode, dropType) => {
	const dragData = draggingNode?.data
	const dropData = dropNode?.data
	let query = {
		...dragData,
	}
	if (dropType === 'inner') {
		query.administrationPid = dropData.administrationId
		query.parentPath = dropData.parentPath
	} else {
		query.administrationPid = dropData.administrationPid
		query.parentPath = dropData.parentPath
	}
	updateDrag({
		...query,
	})
}

const appendNode = (data, newChild) => {
	newChild.children = []
	if (!data.children) {
		data.children = []
	}
	data.children.push(newChild)
	treeData.value = [...treeData.value]
}

const removeNode = (node, data) => {
	const parent = node.parent
	const children = parent.data?.children || parent.children
	const index = children.findIndex((d) => d.id === data.id)
	children.splice(index, 1)
	treeData.value = [...treeData.value]
}

const handleDelete = (node, data) => {
	ElMessageBox.confirm('请确认是否删除该行政区划?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			apiMod.admin_sysadministration_del([data.administrationId]).then((res) => {
				ElMessage({
					type: 'success',
					message: '删除成功!',
				})
				removeNode(node, data)
			})
		})
		.catch(() => {})
}
onMounted(() => {
	getInitData()
	// 不是第一次就刷新
	if(!treeRefreshData.value.XZ_user){
		handleRefresh()
	}
})
defineExpose({
	appendNode,
	removeNode,
})
</script>

<style scoped lang="scss">
.tree-operate {
	visibility: var(--visibility);
}
</style>
